package com.googlecode.jerato.library.store;

import java.sql.*;

import com.googlecode.jerato.core.store.StoreTransaction;
import com.googlecode.jerato.library.SystemException;

public class StoreTransactionImpl implements StoreTransaction{

	protected Connection _conn;
	protected StoreTransactionService _service;
	protected int _lockCount;

	public StoreTransactionImpl(StoreTransactionService service, Connection conn){
		_service = service;
		_conn = conn;
	}

	public Connection getConnection(){
		return _conn;
	}

	public int getLockCount(){
		return _lockCount;
	}
	public void lock(){
		_lockCount++;
	}
	public void unlock(){
		_lockCount--;
	}

	public void commit(){
		if(_conn != null){
			try{
				_conn.commit();
			}
			catch(SQLException se){
				throw new SystemException("Commit failed.", se);
			}
		}
	}
	public void rollback(){
		if(_conn != null){
			try{
				_conn.rollback();
			}
			catch(SQLException se){
				throw new SystemException("Rollback failed.", se);
			}
		}
	}

	public void end(){
		StoreTransactionService service = _service;
		if(service != null){
			service.remove(this);
		}
		if(_conn != null){
			try{
				try{
					_conn.rollback();
				}
				finally{
					_conn.close();
				}
			}
			catch(SQLException se){
				//ignore
			}
			_conn = null;
		}
		_lockCount = 0;
	}
}
